package com.pureut.production.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pureut.common.core.exception.GlobalException;
import com.pureut.common.core.utils.bean.BeanUtils;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.security.utils.SecurityUtils;
import com.pureut.production.domain.GroupManagement;
import com.pureut.production.domain.GroupManagementDetail;
import com.pureut.production.domain.SysShopModeling;
import com.pureut.production.domain.dto.*;
import com.pureut.production.domain.vo.GroupManagementDetailVo;
import com.pureut.production.domain.vo.GroupManagementVo;
import com.pureut.production.mapper.GroupManagementDetailMapper;
import com.pureut.production.mapper.GroupManagementMapper;
import com.pureut.production.service.GroupManagementDetailService;
import com.pureut.production.service.GroupManagementService;
import com.pureut.system.api.FeignService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: CM
 * @date: 2023/2/7  16:14
 */
@Service
public class GroupManagementServiceImpl extends ServiceImpl<GroupManagementMapper, GroupManagement> implements GroupManagementService {

    /**
     * 班组管理信息
     */
    @Resource
    GroupManagementMapper groupManagementMapper;

    /**
     * 班组管理明细
     */
    @Resource
    GroupManagementDetailMapper groupManagementDetailMapper;

    @Resource
    GroupManagementDetailService groupManagementDetailService;

    @Resource
    FeignService feignService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean add(GroupManagementVo groupManagementVo) {

        List<GroupManagementDetailVo> list = groupManagementVo.getList();


        if (list.size() < 1) {
            throw new GlobalException("至少存在一条线别");
        }

        List<GroupManagementDetailVo> cbList = list
                .stream()
                .collect(
                        Collectors.collectingAndThen(
                                Collectors.toCollection(
                                        () -> new TreeSet<>(
                                                Comparator.comparing(
                                                        tc -> tc.getGroupCalendarTeam() + ";" + tc.getLineCode()))), ArrayList::new));

        if (cbList.size() < list.size()) {
            throw new GlobalException("相同班组不能存在重复线别");
        }

        GroupManagement groupManagements = groupManagementMapper.selectOne(new QueryWrapper<GroupManagement>().lambda().eq(GroupManagement::getGroupCode, groupManagementVo.getGroupCode()));

        if (groupManagements != null) {
            throw new GlobalException("班组编码已经存在");
        }
        GroupManagement groupManagement = new GroupManagement();
        //新增班别信息
        BeanUtils.copyProperties(groupManagementVo, groupManagement);
        groupManagement.setCreateTime(new Date()).setCreateMan(SecurityUtils.getUsername());
        //新增班别信息
        boolean save = save(groupManagement);

        // int insert = 0;
        if (save) {
            GroupManagement groupManagement1 = groupManagementMapper.selectOne(new QueryWrapper<GroupManagement>().lambda().eq(GroupManagement::getGroupCode, groupManagementVo.getGroupCode()));

            List<GroupManagementDetail> arrayList = new ArrayList<>();
            for (GroupManagementDetailVo groupManagementDetailVo : list) {
                GroupManagementDetail groupManagementDetail = new GroupManagementDetail();
                BeanUtils.copyProperties(groupManagementDetailVo, groupManagementDetail);
                groupManagementDetail.setGroupId(groupManagement1.getId());
                arrayList.add(groupManagementDetail);
            }
            groupManagementDetailService.saveBatch(arrayList);
        } else {
            throw new GlobalException("新增失败");
        }
        return save;
    }

    /**
     * 班组管理信息列表查询
     *
     * @param groupManagementVo
     * @return
     */
    @Override
    public List<GroupManagementDto> getList(GroupManagementVo groupManagementVo) {
        return groupManagementMapper.getGroupList(groupManagementVo);
    }

    /**
     * 修改班组管理
     *
     * @param groupManagementVo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean edit(GroupManagementVo groupManagementVo) {
        //查询班组编码
        GroupManagement groupManagement2 = groupManagementMapper.selectById(groupManagementVo.getId());
        //删除所有班别设置
        Long id = groupManagementVo.getId();
        groupManagementMapper.deleteById(id);

        int delete = groupManagementDetailMapper.delete(new QueryWrapper<GroupManagementDetail>().lambda().eq(GroupManagementDetail::getGroupId, id));

        if (delete > 0) {
            List<GroupManagementDetailVo> list = groupManagementVo.getList();


            if (list.size() == 0) {
                throw new GlobalException("至少存在一条线别");
            }

            List<GroupManagementDetailVo> cbList = list
                    .stream()
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(
                                                            tc -> tc.getGroupCalendarTeam() + ";" + tc.getGroupCalenderLine()))), ArrayList::new));

            if (cbList.size() < list.size()) {
                throw new GlobalException("相同班组不能存在重复线别");
            }

            GroupManagement groupManagement = new GroupManagement();
            //新增班别信息
            BeanUtils.copyProperties(groupManagementVo, groupManagement);
            groupManagement.setDeptId(SecurityUtils.getDeptId()).setCreateTime(new Date()).setCreateMan(SecurityUtils.getUsername()).setGroupCode(groupManagement2.getGroupCode());
            //新增班别信息
            boolean save = save(groupManagement);

            // int insert = 0;
            List<GroupManagementDetail> arrayList = new ArrayList<>();
            for (GroupManagementDetailVo groupManagementDetailVo : list) {
                GroupManagementDetail groupManagementDetail = new GroupManagementDetail();
                BeanUtils.copyProperties(groupManagementDetailVo, groupManagementDetail);
                groupManagementDetail.setGroupId(groupManagement.getId());
                arrayList.add(groupManagementDetail);
            }
            groupManagementDetailService.saveBatch(arrayList);
        } else {
            throw new GlobalException("修改失败");
        }

        return delete > 0;
    }

    /**
     * 删除班组信息
     *
     * @param ids
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean remove(String ids) {
        //将ids根据逗号拆分成数组
        List<String> idStr = Arrays.asList(ids.split(","));

        //删除明细
        for (String id : idStr) {
            int delete = groupManagementDetailMapper.delete(new QueryWrapper<GroupManagementDetail>().lambda().eq(GroupManagementDetail::getGroupId, id));
        }
        //删除班组信息
        return groupManagementMapper.deleteBatchIds(idStr) > 0;

    }

    /**
     * 查看单据
     *
     * @param id
     * @return
     */
    @Override
    public GroupManagementDto view(Long id) {
        GroupManagement groupManagement = groupManagementMapper.selectById(id);
        GroupManagementDto groupManagementDto = new GroupManagementDto();
        BeanUtils.copyProperties(groupManagement, groupManagementDto);
        String userName = feignService.getUserName(Long.valueOf(groupManagement.getGroupMonitor()));
        groupManagementDto.setGroupMonitorName(userName);
        List<GroupManagementDetailViewDto> list = groupManagementDetailService.getList(id);
        if (list.size()!=0){
            groupManagementDto.setList(list);
        }else{
            groupManagementDto.setList(new ArrayList<>());
        }
        return groupManagementDto;

    }

    /**
     * 获取车间id
     *
     * @return
     */
    @Override
    public DataIsolationDto getWorkshopId() {

        DataIsolationDto dataIsolationDto = new DataIsolationDto();

        //获取当前登录人员名称
        String username = SecurityUtils.getUsername();

        //获取班组表数据信息
        List<GroupManagement> list = list();
        List<GroupManagement> groupManagementArrayList = new ArrayList<>();
        //比较获取当前登录人员所在班组信息
        for (GroupManagement entity : list) {
            if (username.contains(entity.getGroupMember())) {
                groupManagementArrayList.add(entity);
            }
        }
        //获取明细列表
        List<GroupManagementDetailViewDto> managementDetailViewDtoList = new ArrayList<>();
        for (GroupManagement entity : groupManagementArrayList) {
            List<GroupManagementDetailViewDto> list1 = groupManagementDetailService.getList(entity.getId());
            managementDetailViewDtoList.addAll(list1);
        }
        GroupManagementDetailViewDto groupManagementDetailViewDto = null;
        for (GroupManagementDetailViewDto entity : managementDetailViewDtoList) {
            //获取当前时间
            Date nowTime = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(nowTime);
            Date time = calendar.getTime();
            //判断当前时间是否在开始时间和结束时间之内
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm");
            String time2 = simpleDateFormat.format(time);
            String time3 = simpleDateFormat.format(entity.getStartTime());
            String time4 = simpleDateFormat.format(entity.getEndTime());
            if (time2.compareTo(time3) > 0 && time2.compareTo(time4) < 0) {
                groupManagementDetailViewDto = entity;
                break;
            }
        }
        if (groupManagementDetailViewDto == null) {
            throw new GlobalException("未进行工厂日历配置");
        }
        //根据线别编码获取车间id
        String lineCode = groupManagementDetailViewDto.getLineCode();
        AjaxResult workshopId = feignService.getWorkshopId(lineCode);
        SysShopModeling data = JSON.parseObject(JSON.toJSONString(workshopId.get("data")), SysShopModeling.class);

        dataIsolationDto.setWorkshopId(data.getParentId());
        return dataIsolationDto;
    }

    /**
     * 根据班组编码获取班组信息，班长信息及班组成员（设备模块fegin调用）
     *
     * @param groupCode
     * @return
     */
    @Override
    public GroupDataDto getDataByGroupCode(String groupCode) {
        GroupManagement groupManagement = groupManagementMapper.selectOne(new QueryWrapper<GroupManagement>().lambda().eq(GroupManagement::getGroupCode, groupCode));
        GroupDataDto groupDataDto = new GroupDataDto();
        groupDataDto.setGroupName(groupManagement.getGroupName());
        groupDataDto.setGroupMonitorName(groupManagement.getGroupMonitorName());
        groupDataDto.setGroupMonitor(Long.valueOf(groupManagement.getGroupMonitor()));
        //获取班组成员名称列表
        List<String> groupManagementList = Arrays.asList(groupManagement.getGroupMember().split(","));
        //获取班组成员id列表
        List<String> groupManagementIdList = Arrays.asList(groupManagement.getGroupMemberId().split(","));

        List<GroupMemberDto> result = new ArrayList<>();
        for (int i = 0; i < groupManagementIdList.size(); i++) {
            GroupMemberDto groupMemberDto = new GroupMemberDto();
            groupMemberDto.setId(Long.parseLong(groupManagementIdList.get(i)));
            groupMemberDto.setName(groupManagementList.get(i));
            result.add(groupMemberDto);
        }

        groupDataDto.setGroupMemberList(result);
        return groupDataDto;
    }


}
